//
//  MovieViewController.m
//  Movie
//
//  Created by cjy on 16/3/23.
//  Copyright © 2016年 HY. All rights reserved.
//

#import "MovieViewController.h"
#import "NetworkHandeler.h"
#import "MovieModel.h"
#import "MovieTableViewCell.h"
#import "MovieChange.h"
#import "MovieScrollView.h"
#import "MovieImageView.h"
#import "MovieContentView.h"
#import <UIImageView+WebCache.h>
#import "PlayerViewController.h"
#import <SDWebImageManager.h>
#import "AFHTTPRequestOperation.h"


#define screenFrame [UIScreen mainScreen].bounds


@interface MovieViewController ()<UITableViewDataSource,UITableViewDelegate,NetworkHandelerDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *arr;


@property (nonatomic, strong) NSMutableDictionary *selectDic;
@property (nonatomic, strong) NSMutableArray *dateArray;
@property (nonatomic, strong) NSIndexPath *flagIndexPath;
@property (nonatomic, strong) UIButton *tishi;

@end

@implementation MovieViewController

#pragma mark ---------- 数据解析 -----------

//懒加载
- (NSMutableDictionary *)selectDic{
    
    if (!_selectDic) {
        
        _selectDic = [[NSMutableDictionary alloc]init];
        
    }
    return _selectDic;
}

- (NSMutableArray *)dateArray{
    
    if (!_dateArray) {
        _dateArray = [[NSMutableArray alloc]init];
    }
    return _dateArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    

    
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor colorWithRed:28 / 255.f green:28 / 255.f blue:28 / 255.f alpha:1];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"CT"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    [self handle];
    [self createtableView];
}



- (void)createtableView{



    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;    
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;

    [self.tableView registerClass:[MovieTableViewCell class] forCellReuseIdentifier:@"pool"];

}

// 解析区头标题
- (void)handle{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"yyyyMMdd"];
    
    NSDate *date = [NSDate date];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    

    
    NSString *str =[NSString stringWithFormat: @"http://baobab.wandoujia.com/api/v1/feed?num=10&date=%@&vc=67&u=011f2924aa2cf27aa5dc8066c041fe08116a9a0c&v=1.8.0&f=iphone",dateString];

    [NetworkHandeler handelerJSONWithURL:str delegate:self];

}

- (void)handelerDidComplete:(id)result{
    
    
    self.arr = [NSMutableArray array];
    NSArray *arrdailyList = [result objectForKey:@"dailyList"];

    for (NSDictionary *dicvideoList in arrdailyList) {
        NSArray *arrvideoList = [dicvideoList objectForKey:@"videoList"];
        
        
        for (NSDictionary *dic in arrvideoList) {
            
            
            
            _model = [[MovieModel alloc]init];
            
            
            [_model setValuesForKeysWithDictionary:dic];
            
            _model.playUrl = [dic objectForKey:@"playUrl"];
            [self.arr addObject:self.model];
        }
        NSString *date = [[[dicvideoList objectForKey:@"date" ] stringValue] substringToIndex:10];
        
        [self.selectDic setValue:self.arr forKey:date];
        
    }
    
    
    
    
    // 枚举类型 block 排序
    NSComparisonResult (^priceBlock)(NSString *, NSString *) = ^(NSString *string1, NSString *string2){
        
        NSInteger number1 = [string1 integerValue];
        NSInteger number2 = [string2 integerValue];
        
        if (number1 > number2) {
            return NSOrderedAscending;
        }else if(number1 < number2){
            return NSOrderedDescending;
        }else{
            return NSOrderedSame;
        }
        
    };
    
    
    self.dateArray = [[[self.selectDic allKeys] sortedArrayUsingComparator:priceBlock]mutableCopy];
    

    [self.tableView reloadData];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dateArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[self.selectDic objectForKey: self.dateArray[section]] count];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];

    return cell;

}

// 头标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    
    NSString *string = self.dateArray[section];
    
    long long int date1 = (long long int)[string intValue];
    
    NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:date1];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"MMdd"];
    
    NSString *dateString = [dateFormatter stringFromDate:date2];
    
    return dateString;
    
}


#pragma mark -- 视图出现的时候
-(void)tableView:(UITableView *)tableView willDisplayCell:(MovieTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{

    
   
    _model = self.selectDic[self.dateArray[indexPath.section]][indexPath.row];

    
    CATransform3D rotation;//3D旋转
    
    rotation = CATransform3DMakeTranslation(0 ,50 ,20);
    
    //逆时针旋转
    
    rotation = CATransform3DScale(rotation, 0.9, .9, 1);
    
    rotation.m34 = 1.0/ -600;
    
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    
    cell.layer.transform = rotation;
    
    [UIView beginAnimations:@"rotation" context:NULL];
    //旋转时间
    [UIView setAnimationDuration:0.3];
    cell.layer.transform = CATransform3DIdentity;
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    [UIView commitAnimations];

    [cell cellOffset];
    cell.model = _model;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{


    return 200;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 30;
}


#pragma mark - 传参数
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
        //添加翻页效果
    if ([scrollView isEqual:_change.scrollView]) {
            
            for (MovieImageView *subView in scrollView.subviews) {
//                
                if ([subView respondsToSelector:@selector(imageOffset)] ) {
                    [subView imageOffset];
                }
        
                self.tabBarController.tabBar.hidden = YES;
   
                
                
            }
            
            CGFloat x = self.change.scrollView.contentOffset.x;
            
            CGFloat off = ABS( ((int)x % (int)kWidth) - kWidth/2) /(kWidth/2) + .2;
            
            [UIView animateWithDuration:1.0 animations:^{
                self.change.playView.alpha = off;
                self.change.contentView.titleLabel.alpha = off + 0.3;
                self.change.contentView.littleLabel.alpha = off + 0.3;
                self.change.contentView.lineView.alpha = off + 0.3;
                self.change.contentView.descripLabel.alpha = off + 0.3;
         
            }];
        
        } else {
            
            
#pragma mark -- 视差效果
            NSArray<MovieTableViewCell *> *array = [self.tableView visibleCells];
            
            [array enumerateObjectsUsingBlock:^(MovieTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                [obj cellOffset];
            }];
            
        }
        
    }

    


#pragma mark - cell 点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [ self showImageAtIndexPath:indexPath];
    self.tabBarController.tabBar.hidden = YES;
    self.model = self.selectDic[self.dateArray[indexPath.section]][indexPath.row];
    self.flagIndexPath = indexPath;
    
}

- (void)showImageAtIndexPath:(NSIndexPath *)indexPath{


    self.tabBarController.tabBar.hidden = YES;

    _array = _selectDic[_dateArray[indexPath.section]];
    _currentIndexPath = indexPath;
    
    MovieTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    CGRect rect = [cell convertRect:cell.bounds toView:nil];
    CGFloat y = rect.origin.y;
    
    _change = [[MovieChange alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) imageArray:_array index:indexPath.row];
    
    _change.offsetY = y;
    _change.animationTrans = cell.picture.transform;
    _change.animationView.picture.image = cell.picture.image;
    
    _change.scrollView.delegate = self;
    
    [[self.tableView superview] addSubview:_change];
    //添加轻扫手势 返回主界面
    
    UISwipeGestureRecognizer *Swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(panAction:)];
    
    _change.contentView.userInteractionEnabled = YES;
    
    Swipe.direction = UISwipeGestureRecognizerDirectionUp;
    
    [_change.contentView addGestureRecognizer:Swipe];
    
    //添加点击播放手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    
    [_change.scrollView addGestureRecognizer:tap];
    
    [_change aminmationShow];
    
}


- (void)tapAction{

    PlayerViewController *play = [[PlayerViewController alloc]init];

    play.UrlString = _model.playUrl;
    play.receiveModel = _model;
    
    [self showDetailViewController:play sender:nil];

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:_change.scrollView]) {
        
        
        // 当前页数 算法
        int index = floor((_change.scrollView.contentOffset.x - scrollView.frame.size.width / 2) / scrollView.frame.size.width) + 1;
        
        _change.scrollView.currentIndex = index;
        
        self.currentIndexPath = [NSIndexPath indexPathForRow:index inSection:self.currentIndexPath.section];
        
        [self.tableView scrollToRowAtIndexPath:self.currentIndexPath atScrollPosition:(UITableViewScrollPositionMiddle) animated:NO];
        
        [self.tableView setNeedsDisplay];
        MovieTableViewCell *cell = [self.tableView cellForRowAtIndexPath:self.currentIndexPath];
        
        [cell cellOffset];
        
        CGRect rect = [cell convertRect:cell.bounds toView:nil];
        _change.animationTrans = cell.picture.transform;
        _change.offsetY = rect.origin.y;
        
//        self.model = self.selectDic[self.dateArray[_flagIndexPath.section]][index];

        
       _model = _array[index];
        

        [_change.contentView setData:self.model];
        
        [_change.animationView.picture sd_setImageWithURL:[NSURL URLWithString: _model.coverForDetail]];
    
    }
}

#pragma mark -------------- 平移手势触发事件 -----------

- (void)panAction:(UISwipeGestureRecognizer *)swipe{
    
    [_change animationDismissUsingCompeteBlock:^{
        
        _change = nil;
    }];
    
    self.tabBarController.tabBar.hidden = NO;

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
